package cn.wolfcode.wolf2w.strategy.service.impl;

import cn.wolfcode.wolf2w.common.core.constant.SecurityConstants;
import cn.wolfcode.wolf2w.common.core.domain.R;
import cn.wolfcode.wolf2w.common.security.utils.SecurityUtils;
import cn.wolfcode.wolf2w.member.api.RemoteUserInfoService;
import cn.wolfcode.wolf2w.member.api.domain.UserInfo;
import cn.wolfcode.wolf2w.strategy.api.domain.StrategyComment;
import cn.wolfcode.wolf2w.strategy.mapper.StrategyCommentMapper;
import cn.wolfcode.wolf2w.strategy.query.StrategyCommentQuery;
import cn.wolfcode.wolf2w.strategy.service.IStrategyCommentService;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 攻略评论Service业务层处理
 * 
 * @author dafei
 * @date 2023-11-27
 */
@Service
@Transactional
public class StrategyCommentServiceImpl extends ServiceImpl<StrategyCommentMapper,StrategyComment> implements IStrategyCommentService {


    @Autowired
    private RemoteUserInfoService remoteUserInfoService;

    @Override
    public IPage<StrategyComment> queryPage(StrategyCommentQuery qo) {
        IPage<StrategyComment> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
        lambdaQuery()
                .eq(qo.getStrategyId() != null, StrategyComment::getStrategyId, qo.getStrategyId())
                .page(page);
        //评论-用户头像
        for (StrategyComment record : page.getRecords()) {
            R<UserInfo> ret = remoteUserInfoService.getOne(record.getUserId(), SecurityConstants.INNER);
            if(ret != null && R.isSuccess(ret)){
                record.setUser(ret.getData());
            }
        }
        return page;
    }

    //1：点赞   2：取消点赞
    @Override
    public boolean thumbsup(Long cid) {
        StrategyComment comment = super.getById(cid);

        // 获取点赞列表，
        List<Long> list = comment.getThumbupidsList();

        boolean flag = false;
        // 判断当前用户id是否在列表中
        Long uid = SecurityUtils.getUserId();
        if(list.contains(uid)){
            //是： 当前为取消操作， 点赞数-1， 将用户id移除出点赞列表
            comment.setThumbnum(comment.getThumbnum() - 1);
            list.remove(uid);

        }else{
            //不是：当前为点赞操作， 点赞数+1 将用户id添加到点赞列表
            comment.setThumbnum(comment.getThumbnum() + 1);
            list.add(uid);
            flag = true;
        }

        //更新
        //list.stream().map(String::valueOf).collect(Collectors.joining(","));
        comment.setThumbupids(StringUtils.join(list, "," ));
        super.updateById(comment);

        return flag;
    }

}
